package com.xiaotou.utils;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.xiaotou.db.pojo.WbUser;

public class AuthUtils {

	private static final String TOKENSECRET = "tokenSecret";
	private static final String LOGINUSER = "loginUser";
	private static final String COOKIE_NAME = "any";

	public static void setTokenSecret(String tokenSecret) {
		ActionContext.getContext().getSession().put(TOKENSECRET, tokenSecret);
	}

	public static String getTokenSecrct() {
		return (String) ActionContext.getContext().getSession()
				.get(TOKENSECRET);
	}

	public static void setLoginUser(WbUser wbUser) {
		wbUser.getAppUser().getMoney();
		ActionContext.getContext().getSession().put(LOGINUSER, wbUser);
	}

	public static WbUser getLoginUser() {
		return (WbUser) ActionContext.getContext().getSession().get(LOGINUSER);
	}

	public static void putUserIdToCookie(Long userId) {
		final Cookie cookie = new Cookie(COOKIE_NAME, userId.toString());
		cookie.setMaxAge(3600 * 24 * 365);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public static Long getUserIdFromCookie() {
		Long userId = null;
		final Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (COOKIE_NAME.equals(cookie.getName())) {
					userId = Long.valueOf(cookie.getValue());
				}
			}
		}
		return userId;
	}
}
